package pdf;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author huu
 * @create 2025-08-23-15:04
 * 需求：一个Pdf文件我读取它耗时很久，我希望自建一个缓冲区，将Pdf文件内容读取到缓冲区中，然后从缓冲区中读取数据
 */
public class InputBuffer extends InputStream {
    private final FileInputStream fileInputStream;
    private byte[] buffer = new byte[8192];
    private int postion = -1;
    private int capacity = -1;
    public InputBuffer(FileInputStream fileInputStream) {
        this.fileInputStream = fileInputStream;
    }
    @Override
    public int read() throws IOException {
        if(bufferCanRead()){
            return readFromBuffer();
        }
        refreshBuffer();
        if(!bufferCanRead()){
            return -1;
        }
        return readFromBuffer();
    }

    private void refreshBuffer() throws IOException {
        //刷新缓冲区
        capacity = this.fileInputStream.read(buffer);
        postion = 0;
    }

    private int readFromBuffer() {
        //& 0xff默认有符号，0xff无符号
        return buffer[postion++] & 0xff;
    }

    private boolean bufferCanRead() {
        if(capacity == -1){
            return false;
        }
        return postion < capacity;
    }

    @Override
    public void close() throws IOException {
        super.close();
        buffer = null;
    }
}
